package com.ljy.my_study.spring.tiny.study7.beans.xml;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.ljy.my_study.spring.tiny.study7.beans.AbstractBeanDefinitionReader;
import com.ljy.my_study.spring.tiny.study7.beans.BeanDefinition;
import com.ljy.my_study.spring.tiny.study7.beans.BeanReference;
import com.ljy.my_study.spring.tiny.study7.beans.io.ResourceLoader;

public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader{

	public XmlBeanDefinitionReader(ResourceLoader resourceLoader) {
		super(resourceLoader);
	}

	@Override
	public void loadBeanDefinitions(String location) throws Exception {
		InputStream inputStream=getResourceLoader().getResource(location).getInputStream();
		doLoadBeanDefinitions(inputStream);
	}

	protected void doLoadBeanDefinitions(InputStream inputStream) throws Exception {
		DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
		DocumentBuilder builder=factory.newDocumentBuilder();
		Document document=builder.parse(inputStream);
		registerBeanDefinitions(document);
		inputStream.close();
	}

	private void registerBeanDefinitions(Document document) {
		Element root=document.getDocumentElement();
		NodeList nodeList=root.getChildNodes();
		for(int i=0;i<nodeList.getLength();i++) {
			Node node=nodeList.item(i);
			if(node instanceof Element) {
				Element e=(Element)node;
				System.out.println(node.getLocalName());
				System.out.println(node.getNodeName());
				if(!"bean".equals(e.getTagName())) {
					continue;
				}
				String name=e.getAttribute("name");
				String className=e.getAttribute("class");
				BeanDefinition beanDefinition =new BeanDefinition();
				beanDefinition.setClassName(className);
				parsePropertyValues(e,beanDefinition);
				getRegistry().put(name,beanDefinition);
			}
			
		}
	}

	private void parsePropertyValues(Element e,BeanDefinition beanDefinition) {
		NodeList proNodes=e.getElementsByTagName("property");
		for(int i=0;i<proNodes.getLength();i++) {
			Node proNode=proNodes.item(i);
			if(proNode instanceof Element) {
				Element proEle=(Element)proNode;
				String name=proEle.getAttribute("name");
				String value=proEle.getAttribute("value");
				if(value==null||value.length()==0) {
					String ref=proEle.getAttribute("ref");
					if(ref==null||ref.length()==0) {
						throw new IllegalArgumentException();
					}
					BeanReference beanReference=new BeanReference();
					beanReference.setName(ref);
					beanDefinition.getPropertyValues().addPropertyValue(name, beanReference);
				}else {
					beanDefinition.getPropertyValues().addPropertyValue(name, value);
				}
			}
		}
	}
	
	
}
